<template>
	<view class="history">
		<view class="history-title">
			<!-- 历史记录的文字 -->
			<span>历史记录</span>
			<!-- 删除历史记录的图标 -->
			<span
				class="clear-history"
				@click="clearHistory"
			>
				<i class="certishare-icon">
					<span>&#xe67e;</span>
				</i>
			</span>
		</view>

		<!-- 展示历史记录 -->
		<view class="history-list">
			<view
				class="no-history"
				v-if="!historyList.length"
			>
				<span>当前没有历史记录 (＾Ｕ＾)ノ~ＹＯ</span>
			</view>
			<view
				v-for="(item, index) in displayedHistory"
				:key="index"
				class="history-item"
				@click="toSearch(index)"
			>
				{{ item }}
			</view>
		</view>
		<view
			class="show-more"
			v-if="showMore"
			@tap="toggleShowMore"
		>
			{{ showMoreText }}
		</view>
		<u-modal
			:show="showModal"
			:content="modalContent"
			:title="modalTitle"
			:showCancelButton="true"
			:closeOnClickOverlay="true"
			@confirm="clearStoreHistoryList"
			@cancel="closeModal"
		></u-modal>
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
export default {
	data() {
		return {
			historyList: [],
			showMore: false,
			maxDisplayedHistory: 8,
			showMoreText: '查看更多历史记录',
			showModal: false,
			modalTitle: '确认清除历史记录',
			modalContent: '确定要清除所有历史记录吗？',
			modalCancelText: '取消'
		};
	},
	computed: {
		displayedHistory() {
			return this.showMore ? this.historyList : this.historyList.slice(0, this.maxDisplayedHistory);
		}
	},
	methods: {
		toggleShowMore() {
			this.showMore = !this.showMore;
			this.showMoreText = this.showMore ? '收起历史记录' : '查看更多历史记录';
		},
		showHistory() {
			let d = this.displayedHistory();
			console.log(d);
		},
		clearHistory() {
			if (!this.historyList.length) {
				this.showToast();
			} else {
				this.showModal = true;
			}
		},
		// 关闭模态框
		closeModal() {
			this.showModal = false;
		},
		// 获取历史记录列表
		getStoreHistoryList() {
			this.historyList = uni.getStorageSync('historyList') || [];
		},
		// 清空历史记录列表
		clearStoreHistoryList() {
			this.historyList = [];
			uni.setStorageSync('historyList', this.historyList);
			this.showModal = false;
		},
		showToast() {
			this.$refs.uToast.show({
				type: 'default',
				message: '历史记录为空'
			});
		},
		toSearch(index) {
			const key = this.displayedHistory[index];
			uni.navigateTo({
				url: `/pages/search-result-page/search-result-page?search=${key}`
			});
		}
	},

	mounted() {
		uni.$on('updataHistory', this.getStoreHistoryList);
		this.getStoreHistoryList();
	}
};
</script>

<style>
.history {
	margin-top: 30rpx;
}
.history-title {
	font-size: 18px;
	font-weight: bold;
	margin-bottom: 10px;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.history-list {
	display: flex;
	flex-wrap: wrap;
}
.no-history {
	font-size: 12px;
	color: #999;
	margin: 0 auto;
}
.history-item {
	padding: 5px 10px;
	border: 1px solid #ccc;
	border-radius: 50px;
	margin: 5px;
	font-size: 20rpx;
	color: rgba(0, 0, 0, 0.7);
}

.show-more {
	text-align: center;
	color: #007bff;
	margin-top: 10px;
}
</style>
